/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jule.clases.treeFiles;

import java.io.File;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.tree.TreeNode;

public class DirectoryNode implements TreeNode {
       private File file;

       private DirectoryNode parentNode;

       private Vector childNodes = new Vector();

       public DirectoryNode(File file) {
               if (file == null) {
                       throw new IllegalArgumentException("File object is null");
               }
               if (file.isDirectory()) {
                       this.file = file;
                       populateChildNodes(Arrays.asList(file.listFiles()));

               } else {
                       throw new IllegalArgumentException(
                                       "File object is not a directory. It could be a file");
               }
       }

       public DirectoryNode(File file, DirectoryNode parentNode) {
               if (file == null) {
                       throw new IllegalArgumentException("File object is null");
               }
               if (file.isDirectory()) {
                       this.file = file;
                       populateChildNodes(Arrays.asList(file.listFiles()));
               } else {
                       throw new IllegalArgumentException(
                                       "File object is not a directory. It could be a file");
               }
               this.parentNode = parentNode;
       }

       public Enumeration children() {
               return childNodes.elements();
       }

       public boolean getAllowsChildren() {
               return true;
       }

       public TreeNode getChildAt(int arg0) {
               return (TreeNode) childNodes.elementAt(arg0);
       }

       public int getChildCount() {
               return childNodes.size();
       }

       public int getIndex(TreeNode arg0) {
               return childNodes.indexOf(arg0);
       }

       public TreeNode getParent() {
               return parentNode;
       }

       public boolean isLeaf() {
               return false;
       }

       public String toString() {
               return file.getName();
       }

       private void populateChildNodes(List files) {
               Iterator i = files.iterator();
               while (i.hasNext()) {
                       File file = (File) i.next();
                       if (file.isFile()) {
                               childNodes.add(new FileNode(file, this));
                       } else {
                           // to avoid svn directories of subversion....
                           if (!file.toString().contains("svn"))
                                childNodes.add(new DirectoryNode(file, this));
                       }
               }
       }
}

